package dameng

import (
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/text/gregex"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/gogf/gf/v2/util/gconv"
	"strings"
)

const (
	linkPattern = `(\w+):([\w\-\$]*):(.*?)@(\w+?)\((.+?)\)/{0,1}([^\?]*)\?{0,1}(.*)`
)

func getCurrentSchema(d *Driver) (name string) {
	name = d.GetConfig().User
	extra := d.GetConfig().Extra
	if extra != "" {
		m, err := gstr.Parse(strings.ToLower(extra))
		if err == nil {
			for k, v := range m {
				if strings.ToLower(k) == "schema" {
					name = v.(string)
					break
				}
			}
		}
	}
	return
}

func parseConfigNodeLink(node *gdb.ConfigNode) *gdb.ConfigNode {
	var match []string
	if node.Link != "" {
		match, _ = gregex.MatchString(linkPattern, node.Link)
		if len(match) > 5 {
			node.Type = match[1]
			node.User = match[2]
			node.Pass = match[3]
			node.Protocol = match[4]
			array := gstr.Split(match[5], ":")
			if node.Protocol == "file" {
				node.Name = match[5]
			} else {
				if len(array) == 2 {
					// link with port.
					node.Host = array[0]
					node.Port = array[1]
				} else {
					// link without port.
					node.Host = array[0]
				}
				node.Name = match[6]
			}
			if len(match) > 6 && match[7] != "" {
				node.Extra = match[7]
			}
			node.Link = ""
		}
	}
	if node.Extra != "" {
		if m, _ := gstr.Parse(node.Extra); len(m) > 0 {
			_ = gconv.Struct(m, &node)
		}
	}
	// Default value checks.
	if node.Charset == "" {
		node.Charset = `"`
	}
	if node.Protocol == "" {
		node.Protocol = "tcp"
	}
	return node
}
